package com.haotunet.app.goldtreasure.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.haotunet.app.goldtreasure.R;
import com.haotunet.app.goldtreasure.model.BaseModel;
import com.haotunet.app.goldtreasure.model.CardInfo;
import com.haotunet.app.goldtreasure.model.CardModel;
import com.haotunet.app.goldtreasure.model.TipsInfo;
import com.haotunet.app.goldtreasure.net.ActionUtil;
import com.haotunet.app.goldtreasure.other.Interface.OnPassBackListener;
import com.haotunet.app.goldtreasure.utils.ActivityUtils;
import com.haotunet.app.goldtreasure.utils.ShareStore;
import com.haotunet.app.goldtreasure.utils.Strs;
import com.haotunet.app.goldtreasure.utils.UIHelper;
import com.haotunet.app.goldtreasure.views.DialogWidget;
import com.haotunet.app.goldtreasure.views.MyAlertDialog;
import com.haotunet.app.goldtreasure.views.PayPasswordView;
import com.haotunet.app.goldtreasure.views.PayPasswordView.OnPayListener;
import com.haotunet.app.goldtreasure.views.TipPopupView;
import com.haotunet.app.goldtreasure.views.TitleView;

import java.util.List;

public class WithDrawalsActivity extends BaseActivity implements OnClickListener {
    private TitleView mTitleView;
    private TextView mBankName;
    private TextView mTailNum;
    private TextView mWithdrawTip;
    private EditText mAmountTxt;
    private TextView mWithDrawAllBtn;
    private EditText mOpenBnakTxt;
    private Button btnSubmit;
    private LinearLayout mTipLayout;
    private RelativeLayout openBnakLayout;
    private String openBank;
    private final int GET_MY_BANKCARD_LIST_SUCCESS = 2;
    private List<CardInfo> cardList;
    private DialogWidget mDialogWidget;
    private String tipTxt;
    private String withDrawAmount;
    private Handler handle = new Handler() {

        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case GET_MY_BANKCARD_LIST_SUCCESS:
                    CardModel model = (CardModel) msg.obj;
                    cardList = model.getBankCards();
                    if (cardList.size() > 0) {
                        mBankName.setText(cardList.get(0).getBankName());
                        mTailNum.setText("(尾号" + cardList.get(0).getBankCardlast4() + ")");
                        mAmountTxt.setHint("本次最多可提现" + cardList.get(0).getWithdrawalMoney() + "元");
                    } else {
                        mBankName.setText("无绑定银行卡");
                    }
                    break;

                default:
                    break;
            }
        }

    };
    private PayPasswordView passwordView;
    private ShareStore shareStore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_withdrawals);
        shareStore = new ShareStore(WithDrawalsActivity.this);
        initView();
        initData();
        getWithDrawTips();
    }

    private void initData() {
        ActionUtil actionUtil = new ActionUtil(WithDrawalsActivity.this);
        actionUtil.getMyBankCardList();
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()) {
                    return;
                }
                CardModel cardModel = (CardModel) model;
                if (cardModel == null) {
                    UIHelper.showToast(WithDrawalsActivity.this, getString(R.string.rank_fail));
                    return;
                }
                if (cardModel.getErrorMsg() != null) {
                    if (cardModel.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(WithDrawalsActivity.this, getString(R.string.crowding_in_tips_txt));
                    } else {
                        UIHelper.showToast(WithDrawalsActivity.this, cardModel.getErrorMsg());
                    }
                } else {
                    Message msg = new Message();
                    msg.what = GET_MY_BANKCARD_LIST_SUCCESS;
                    msg.obj = cardModel;
                    handle.sendMessage(msg);
                }
            }
        });
    }

    private void getWithDrawTips() {
        ActionUtil actionUtil = new ActionUtil(WithDrawalsActivity.this);
        actionUtil.getTips(2);
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()) {
                    return;
                }
                TipsInfo tipInfo = (TipsInfo) model;
                if (tipInfo == null) {
                    UIHelper.showToast(WithDrawalsActivity.this, getString(R.string.rank_fail));
                    return;
                }
                if (tipInfo.getErrorMsg() != null) {
                    if (tipInfo.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(WithDrawalsActivity.this, getString(R.string.crowding_in_tips_txt));
                    } else {
                        UIHelper.showToast(WithDrawalsActivity.this, tipInfo.getErrorMsg());
                    }
                } else {
                    tipTxt = tipInfo.getTips();
                }
            }

        });

    }

    private void initView() {
        mTitleView = (TitleView) findViewById(R.id.title_view);
        mTitleView.getTitletextView().setVisibility(View.VISIBLE);
        mTitleView.getTitletextView().setText("提现");
        mTitleView.getRightText().setVisibility(View.VISIBLE);
        mTitleView.getRightText().setText("提现记录");
        mTitleView.getRightText().setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(WithDrawalsActivity.this, WithdrawalsRecordAct.class);
                startActivity(intent);
            }
        });
        mTitleView.getBackView().setVisibility(View.VISIBLE);
        mTitleView.getBackView().setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mBankName = (TextView) findViewById(R.id.txt_bank_name);
        mTailNum = (TextView) findViewById(R.id.txt_tail_num);
        mAmountTxt = (EditText) findViewById(R.id.et_withdrawals_amount);
        mWithdrawTip = (TextView) findViewById(R.id.withdraw_tips);
        mWithDrawAllBtn = (TextView) findViewById(R.id.btn_withdrawal_all);
        openBnakLayout = (RelativeLayout) findViewById(R.id.rl_open_bank_layout);
        mOpenBnakTxt = (EditText) findViewById(R.id.et_open_bank);
        mAmountTxt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String inputString = s.toString();
                if (inputString.contains(".")) {
                    if (inputString.length() - 1 - inputString.toString().indexOf(".") > 2) {
                        inputString = (String) inputString.subSequence(0, inputString.indexOf(".") + 3);
                        mAmountTxt.setText(inputString);
                        mAmountTxt.setSelection(inputString.length());
                    }
                }
                if (inputString.trim().substring(0).equals(".")) {
                    inputString = "0";
                    mAmountTxt.setText(inputString);
                    mAmountTxt.setSelection(1);
                }
                if (inputString.startsWith("0") && inputString.trim().length() > 1) {
                    if (!inputString.substring(1, 2).equals(".")) {
                        mAmountTxt.setText(inputString.subSequence(1, 2));
                        mAmountTxt.setSelection(1);
                        return;
                    }
                }
                if (cardList!=null&&cardList.size() > 0) {
                    if (inputString.length() > 0) {
                        mWithdrawTip.setVisibility(View.VISIBLE);
                        double withdrawMoney = Double.parseDouble(inputString);
                        double balance = Double.parseDouble(cardList.get(0).getWithdrawalMoney());
                        if (withdrawMoney > balance) {
                            closeWithdrawBtn();
                            openBnakLayout.setVisibility(View.GONE);
                            mWithdrawTip.setText("可提金额不足");
                        } else if (withdrawMoney > 0 && withdrawMoney <= balance && withdrawMoney <= 50000) {
                            mWithdrawTip.setText("预计3个工作日到账");
                            openWithdrawBtn();
                            openBnakLayout.setVisibility(View.GONE);
                        } else if (withdrawMoney > 50000 && withdrawMoney <= balance) {
                            mWithdrawTip.setText("预计3个工作日到账");
                            openBnakLayout.setVisibility(View.VISIBLE);
                            openWithdrawBtn();
                        }
                    } else {
                        mWithdrawTip.setVisibility(View.GONE);
                        closeWithdrawBtn();
                    }
                } else {
                    closeWithdrawBtn();
                }
            }
        });
        mTipLayout = (LinearLayout) findViewById(R.id.tip_layout);
        btnSubmit = (Button) findViewById(R.id.btn_submit);
        mWithDrawAllBtn.setOnClickListener(this);
        mTipLayout.setOnClickListener(this);
        btnSubmit.setOnClickListener(this);

    }

    private void verifyWithdrawFee() {
        ActionUtil actionUtil = new ActionUtil(WithDrawalsActivity.this);
        actionUtil.verifyWithdrawFee(withDrawAmount);
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()) {
                    return;
                }
                if (model == null) {
                    UIHelper.showToast(WithDrawalsActivity.this, getString(R.string.rank_fail));
                    return;
                }
                if (model.getErrorMsg() != null) {
                    if (model.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(WithDrawalsActivity.this, getString(R.string.crowding_in_tips_txt));
                    } else {
                        UIHelper.showToast(WithDrawalsActivity.this, model.getErrorMsg());
                    }
                } else {
                    if ("true".equals(model.getStatus())) {
                        showWithDrawFeeRemindDialog(model.getInfo());
                    } else {
                        showPayDialog();
                    }
                }
            }

        });
    }

    private void submitWithdrawsApply(String withDrawAmount, String tradePwd) {
        ActionUtil actionUtil = new ActionUtil(WithDrawalsActivity.this);
        actionUtil.submitWithdrawsApply(cardList.get(0).getCardNo(), withDrawAmount, tradePwd, openBank);
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (isFinishing()) {
                    return;
                }
                if (model == null) {
                    UIHelper.showToast(WithDrawalsActivity.this, getString(R.string.rank_fail));
                    return;
                }
                if (model.getErrorMsg() != null) {
                    if (model.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(WithDrawalsActivity.this, getString(R.string.crowding_in_tips_txt));
                    } else {
                        passwordView.clearUi();
                        UIHelper.showToast(WithDrawalsActivity.this, model.getErrorMsg());
                    }
                } else {
                    if ("false".equals(model.getStatus())) {
                        passwordView.clearUi();
                        passwordView.setErrorTip(model.getInfo());
                    } else {
                        setResult(RESULT_OK);
                        passwordView.showSuccessUi();
                        new Thread(new Runnable() {
                            public void run() {
                                try {
                                    Thread.sleep(1000);
                                    ActivityUtils.gotoWithDrawsRecord(WithDrawalsActivity.this);
                                    if (mDialogWidget != null) {
                                        mDialogWidget.dismiss();
                                    }
                                    mDialogWidget = null;
                                    WithDrawalsActivity.this.finish();
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    }
                }
            }
        });
    }

    private void showPayDialog() {
        mDialogWidget = new DialogWidget(WithDrawalsActivity.this, getDecorViewDialog(withDrawAmount));
        mDialogWidget.show();
    }

    private void openWithdrawBtn() {
        btnSubmit.setBackgroundResource(R.drawable.login_btn_bg_formal);
        btnSubmit.setEnabled(true);
    }

    private void closeWithdrawBtn() {
        btnSubmit.setBackgroundResource(R.drawable.login_btn_bg_unclick);
        btnSubmit.setEnabled(false);
    }

    protected View getDecorViewDialog(final String amount) {
        if (shareStore.getInt(Strs.IS_HAD_TRADING_PWD, 0) == 1) {
            passwordView = new PayPasswordView(2, 2, WithDrawalsActivity.this, null, "", null);
        } else {
            passwordView = new PayPasswordView(1, 2, WithDrawalsActivity.this, null, "", null);
        }
        passwordView.setOnPayListener(new OnPayListener() {

            @Override
            public void onSurePay(String password) {
                submitWithdrawsApply(amount, password);
            }

            @Override
            public void onCancelPay() {
                mDialogWidget.dismiss();
                mDialogWidget = null;
            }
        });
        return passwordView.getView();
    }

    private void showWithDrawFeeRemindDialog(String info) {
        new MyAlertDialog(WithDrawalsActivity.this).builder().setTitle(getString(R.string.reminder)).setMsg(info)
                .setCancelable(false).setPositiveButton(getString(R.string.action_positive), true, new OnClickListener() {

            @Override
            public void onClick(View v) {
                showPayDialog();
            }
        }).setNegativeButton(getString(R.string.action_negative), new OnClickListener() {

            @Override
            public void onClick(View v) {

            }
        }).show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_withdrawal_all:
                if (cardList != null && cardList.size() > 0) {
                    mAmountTxt.setText(cardList.get(0).getWithdrawalMoney());
                }
                break;
            case R.id.tip_layout:
                new TipPopupView(WithDrawalsActivity.this, null, tipTxt, R.style.MyDialog).show();
                break;
            case R.id.btn_submit:
                withDrawAmount = mAmountTxt.getText().toString().trim();
                if (TextUtils.isEmpty(withDrawAmount)) {
                    UIHelper.showToast(WithDrawalsActivity.this, "请输入提现金额!");
                    return;
                }
                double amount = Double.parseDouble(withDrawAmount);
                if (amount > 50000) {
                    openBank = mOpenBnakTxt.getText().toString();
                    if (TextUtils.isEmpty(openBank)) {
                        UIHelper.showToast(WithDrawalsActivity.this, "请输入开户行!");
                        return;
                    }
                } else {
                    openBank = "";
                }
                verifyWithdrawFee();
                break;
            default:
                break;
        }
    }

}
